import cookie from "@/utils/store/cookie";

type DebounceCallback = (args: any) => void;

//防抖
export const Debounce = (fun: DebounceCallback, delay: number = 0) => {
    let timer = null;
    return (args: any) => {
        if (timer != null) clearTimeout(timer);
        timer = setTimeout(() => {
            fun(args);
        }, delay);
    };
};

//节流
export const Throttle = (fun: DebounceCallback, delay: number) => {
    let lastTime: number = 0;
    return (args: any) => {
        let nowTime = new Date().getTime();
        if (nowTime - lastTime < delay) return;
        fun(args);
        lastTime = nowTime;
    };
};


export function delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}



export function chooseImage(callback) {
    uni.chooseImage({
        count: 1,
        sourceType: ['album'],
        success: res => {
            uni.getImageInfo({
                src: res.tempFilePaths[0],
                success: image => {
                    console.log(image)
                    uni.showLoading({ title: '图片上传中', mask: true })
                    uni.uploadFile({
                        url: `${import.meta.env.VITE_BASE_URL}/api/upload`,
                        file: image,
                        filePath: image.path,
                        header: {
                            Authorization: 'Bearer ' + uni.getStorageSync('token') ,
                        },
                        name: 'file',
                        success: res => {
                            if (callback) {
                                callback(JSON.parse(res.data).link)
                            }
                        },
                        fail: err => {
                            uni.showToast({
                                title: '上传图片失败',
                                icon: 'none',
                                duration: 2000,
                            })
                        },
                        complete: res => {
                            uni.hideLoading()
                        },
                    })
                },
                fail: err => {
                    uni.showToast({
                        title: '获取图片信息失败',
                        icon: 'none',
                        duration: 2000,
                    })
                },
            })
        },
    })
}
